<?php
namespace addons\mall\controller;

use think\Db;
use addons\mall\model\User;
use addons\mall\library\Service;
use app\common\model\mall\goods\Cat;
use app\common\model\mall\oper\Msgtpl;
use app\common\model\mall\shop\Freight;
use think\Exception;

/**
 * 订单控制器
 */
class Order extends Base{

    public function _initialize(){
        parent::_initialize();
        $this->model = new \app\common\model\mall\order\Order;
    }

    /**
     * 用户订单
     */
    public function add(){

        $list = model('\app\common\model\mall\goods\Cart')->getCartList(true);
        if(empty($list)) $this->error("没有要结算的购物数据！", "/addons/mall/cart/index");

        if ($this->request->isPost()) {
            $params = [];
            $params['deliverType'] = (int)input('deliverType');
            $params['areaId'] = input('s_areaId/d');
            $params['addressId'] = input('post.s_addressId/d');
            $params['payType'] = ((int)input('post.payType')!=0)?1:0;
            $params['memo'] = input('memo/a',[]);
            $params['isUseScore'] = (int)input('isUseScore');
            $params['useScore'] = (int)input('useScore');
            $params['isInvoice'] = ((int)input('post.isInvoice')!=0)?1:0;
            $params['invoiceClient'] = ($params['isInvoice']==1)?input('post.invoiceClient'):'';
            if ($params) {
                $result = false;
                Db::startTrans();
                try {
                    if($params['deliverType']==0){// 配送方式为快递，必须有用户地址
                        //检测地址是否有效
                        $address = model('Address','common\model\mall\user')
                            ->where(['user_id'=>$this->auth->id,'id'=>$params['addressId']])
                            ->field("id,isDefault,status,createtime",true)
                            ->find();
                        if(empty($address)){
                            $this->error("无效的用户地址");
                        }
                        $tmp = explode(',',$address['area_ids']);
                        $address['areaId2'] = $tmp[1];//记录配送城市
                        //准备定单收货信息
                        $address['userName'] = $address['name'] ;
                        $address['userPhone'] = $address['phone'];
                        $address['userAddress'] = $address['area_ids_text'].$address['address'];
                        $address = $address->toArray();
                        unset($address['name'],$address['phone'],$address['address'],$address['user_id'],$address['area_ids_text']);
                    }else{
                        $address = [];
                        $address['name'] = '';
                        $address['address'] = '';
                    }

                    //计算各店铺运费及金额
                    $cart = $this->_getOrderMoney($params,$list);

                    //计算出每个订单应该分配的抵现金额和使用积分
                    $useScoreMoney = $this->_allocScoreMoney($cart);

                    //订单批号
                    $orderunique = $this->model->OrderQnique();
                    //将购物车清单按不同商家拆单
                    foreach ($cart['shop_sum'] as $shop_id =>$shop_sum){
                        //订单号
                        $orderNo = $this->model->OrderNo();
                        //创建一个商家订单
                        $order = [];
                        $order = array_merge($order,$address);//合并收货信息
                        $order['orderNo'] = $orderNo;
                        $order['user_id'] = $this->auth->id;
                        $order['shop_id'] = $shop_id;
                        $order['deliverType'] = $params['deliverType'];
                        $order['payType'] = $params['payType'];
                        $order['goodsMoney'] = $shop_sum;
                        $order['deliverMoney'] = $cart['shop_freight'][$shop_id];
                        $order['totalMoney'] = $order['goodsMoney']+$order['deliverMoney'];
                        $order['useScore'] = $useScoreMoney[$shop_id]['useScore'];
                        $order['scoreMoney'] = $useScoreMoney[$shop_id]['useMoney'];
                        //实付金额要减去积分兑换的金额和店铺总优惠
                        $order['realTotalMoney'] = $order['totalMoney'] - $order['scoreMoney'];
                        $order['needPay'] = $order['realTotalMoney'];
                        if($params['payType']){
                            if($order['needPay']>0){
                                //待付款
                                $order['status'] = "unpay";
                                $order['payis'] = 0;
                            }else{
                                //待发货
                                $order['status'] = "undeliver";
                                $order['payis'] = 1;
                                $order['payFrom'] = 'others';
                            }
                        }
                        else{
                            //待发货
                            $order['status'] = "undeliver";
                            if($order['needPay']==0){
                                $order['payis'] = 1;
                                $order['payFrom'] = 'others';
                            }
                        }
                        //积分
                        $orderScore = 0;
                        //如果开启下单获取积分则有积分
                        if(config('mall.isOrderScore')){
                            $orderScore = User::MoneyGiftScore($order['goodsMoney']);
                        }
                        $order['orderScore'] = $orderScore;
                        $order['isInvoice'] = $params['isInvoice'];
                        if($params['isInvoice']){// 发票信息
                            $order['invoiceJson'] = model('Invoice','common\model\mall\order')->getInviceInfo((int)input('param.invoiceId'),$this->auth->id);// 发票信息
                            $order['invoiceClient'] = $params['invoiceClient'];
                        }else{
                            $order['invoiceJson'] = '';
                            $order['invoiceClient'] = '';
                        }
                        $order['orderRemarks'] = $params['memo'][$shop_id];
                        $order['orderunique'] = $orderunique;
                        $result = $this->model->data($order,true)->isUpdate(false)->allowField(true)->save();

                        if(false !== $result){
                            $order_id = $this->model->getAttr('id');
                            $orderTotalGoods = [];
                            $commissionFee = 0;
                            //创建订单商品记录
                            foreach ($cart['shop_goods_list'][$shop_id] as $gkey =>$goods){
                                $orderGoods = [];
                                $orderGoods['order_id'] = $order_id;
                                $orderGoods['goods_id'] = $gkey;
                                $orderGoods['goodsNum'] = $goods['num'];
                                $orderGoods['goodsPrice'] = $goods['goodsPrice'];
                                $orderGoods['goodsSpecNames'] = $goods['goodsSpecNames'];
                                $orderGoods['salespec_id'] = $goods['salespec_id'];
                                $cat_id = explode(",",$goods['goodscat_ids']);
                                $cat_id = end($cat_id);
                                $orderGoods['commissionRate'] = Cat::getCommissionRate($cat_id);
                                $orderTotalGoods[] = $orderGoods;
                                //计算订单总佣金
                                if((float)$orderGoods['commissionRate']>0){
                                    $commissionFee += round($orderGoods['goodsPrice']*$orderGoods['goodsNum']*$orderGoods['commissionRate']/100,2);
                                }
                                //修改库存
                                if($goods['salespec_id']>0){
                                    Db::name('mall_goods_salespec')->where('id',$goods['salespec_id'])
                                        ->inc('salenum',$goods['num'])
                                        ->dec('specstock',$goods['num'])
                                        ->update();
                                }
                                Db::name('mall_goods_goods')->where('id',$gkey)
                                    ->inc('salenum',$goods['num'])
                                    ->dec('goodsstock',$goods['num'])
                                    ->update();
                            }
                            //创建订单商品
                            Db::name('mall_order_goods')->insertAll($orderTotalGoods);
                            //更新订单佣金
                            $this->model->where('id',$order_id)->update(['commissionFee'=>$commissionFee]);

                            //创建积分流水--如果有抵扣积分就肯定是开启了积分支付
                            if($order['useScore']>0){
                                $score = $order['useScore'];
                                $dataRemarks = "交易订单【".$orderNo."】使用积分".$order['useScore']."个";
                                //购物积分增加日志
                                \app\common\model\User::score($score, $this->auth->id, $dataRemarks);
                            }

                            //判断是否需要发送管理员短信
                            $find = ['${ORDER_NO}'];
                            $replace = [$orderNo];
                            $content = Msgtpl::getMsgByTpl('PHONE_ADMIN_SUBMIT_ORDER', $find, $replace);
                            if ($content != '') {
                                Service::smsAdminNotice($content,'neworder');
                            }

                        }//end if
                    }//end for
                    //删除已选的购物车商品
                    Db::name('mall_goods_cart')->where(['user_id'=>$this->auth->id,'checkis'=>1])->delete();

                    Db::commit();

                    $this->success("",null,$orderunique);

                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        //获取一个用户地址
        $userAddress = \app\common\model\mall\user\Address::getDefaultAddress();
        $this->assign('userAddress',$userAddress);
        return $this->view->fetch();
    }

    /**
     * 游客下单
     */
    public function addVisitor(){
        $tmp_carts = session('TMP_CARTS');
        if(empty($tmp_carts)) $this->error("游客购物车为空！");
        $num = (int)$this->request->get("num");
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            $list = \app\common\model\mall\goods\Cart::getVisitorCart($params['num']);
            if(empty($list)) $this->error("没有要结算的购物数据！");
            $params['isUseScore'] = 0;
            $params['useScore'] = 0;
            if ($params) {
                Db::startTrans();
                try{
                    if($params['deliverType']==0){// 配送方式为快递，必须有用户地址
                        //检测地址是否有效
                        $tmp = explode(',',$params['area_ids']);
                        $params['areaId'] = $tmp[1];//记录配送城市
                        $address = [];
                        $areaNames = \app\common\model\mall\oper\Area::getNamesByIds($params['area_ids']);
                        $address['userAddress'] = $areaNames . $params['userAddress'];
                    }else{
                        $address = [];
                        $address['userName'] = '';
                        $address['userAddress'] = '';
                    }

                    //计算各店铺运费及金额
                    $cart = $this->_getOrderMoney($params,$list);

                    $orderunique = $this->model->OrderQnique();
                    foreach ($cart['shop_sum'] as $shop_id =>$shop_sum) {
                        $orderNo = $this->model->OrderNo();
                        //创建订单
                        $order = [];
                        $order = array_merge($order,$params);//合并收货信息
                        $order = array_merge($order,$address);//合并收货信息
                        $order['orderunique'] = $orderunique;
                        $order['orderNo'] = $orderNo;
                        $order['shop_id'] = $shop_id;
                        $order['ip'] = $this->request->ip();
                        $order['useragent'] = substr($this->request->server('HTTP_USER_AGENT'), 0, 255);
                        $order['goodsMoney'] = $shop_sum;
                        $order['deliverMoney'] = $cart['shop_freight'][$shop_id];
                        $order['totalMoney'] = $order['goodsMoney']+$order['deliverMoney'];
                        $order['scoreMoney'] = 0;
                        $order['useScore'] = 0;
                        $order['orderScore'] = 0;
                        //实付金额要减去积分兑换的金额和店铺总优惠
                        $order['realTotalMoney'] = $order['totalMoney'] - $order['scoreMoney'];
                        $order['needPay'] = $order['realTotalMoney'];
                        if($params['payType']){
                            if($order['needPay']>0){
                                //待付款
                                $order['status'] = "unpay";
                                $order['payis'] = 0;
                            }else{
                                //待发货
                                $order['status'] = "undeliver";
                                $order['payis'] = 1;
                                $order['payFrom'] = 'others';
                            }
                        }
                        else{
                            //待发货
                            $order['status'] = "undeliver";
                            if($order['needPay']==0){
                                $order['payis'] = 1;
                                $order['payFrom'] = 'others';
                            }
                        }
                        $result = $this->model->data($order,true)->isUpdate(false)->allowField(true)->save();

                        if(false !== $result){
                            $order_id = $this->model->getAttr('id');
                            $orderTotalGoods = [];
                            $commissionFee = 0;
                            //创建订单商品记录
                            foreach ($cart['shop_goods_list'][$shop_id] as $gkey =>$goods) {
                                $orderGoods = [];
                                $orderGoods['order_id'] = $order_id;
                                $orderGoods['goods_id'] = $gkey;
                                $orderGoods['goodsNum'] = $params['num'];
                                $orderGoods['goodsPrice'] = $goods['goodsPrice'];
                                $orderGoods['goodsSpecNames'] = $goods['goodsSpecNames'];
                                $orderGoods['salespec_id'] = $goods['salespec_id'];
                                $cat_id = explode(",", $goods['goodscat_ids']);
                                $cat_id = end($cat_id);
                                $orderGoods['commissionRate'] = Cat::getCommissionRate($cat_id);
                                $orderTotalGoods[] = $orderGoods;
                                //计算订单总佣金
                                if ((float)$orderGoods['commissionRate'] > 0) {
                                    $commissionFee += round($orderGoods['goodsPrice'] * $orderGoods['goodsNum'] * $orderGoods['commissionRate'] / 100, 2);
                                }
                                //如果是货到付款，则修改库存
                                if (!$params['payType']) {
                                    if ($goods['salespec_id'] > 0) {
                                        Db::name('mall_goods_salespec')->where('id', $goods['salespec_id'])
                                            ->inc('salenum', $goods['num'])
                                            ->dec('specstock', $goods['num'])
                                            ->update();
                                    }
                                    Db::name('mall_goods_goods')->where('id', $gkey)
                                        ->inc('salenum', $goods['num'])
                                        ->dec('goodsstock', $goods['num'])
                                        ->update();
                                }//如果是在线支付，则在支付后修改库存
                            }
                            //创建订单商品
                            Db::name('mall_order_goods')->insertAll($orderTotalGoods);
                            //更新订单佣金
                            $this->model->where('id',$order_id)->update(['commissionFee'=>$commissionFee]);

                            //如果是货到付款，则判断是否需要发送管理员短信
                            if (!$params['payType']) {
                                $find = ['${ORDER_NO}'];
                                $replace = [$orderNo];
                                $content = Msgtpl::getMsgByTpl('PHONE_ADMIN_SUBMIT_ORDER', $find, $replace);
                                if ($content != '') {
                                    Service::smsAdminNotice($content, 'neworder');
                                }
                            }
                        }
                    }
                    if($params['payType']){
                        $carts = session('TMP_CARTS');
                        $carts['orderNo'] = $orderunique;
                        session('TMP_CARTS',$carts);
                    }else{
                        //删除session的购物车商品
                        session('TMP_CARTS',null);
                    }

                    Db::commit();
                    $this->success("","/addons/mall/order/onlinePayCode/orderNo/".$orderunique);

                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->assign('num',$num);
        return $this->view->fetch();
    }

    /**
     * 分配一批多单时使用积分支付的可用积分和抵现金额
     */
    public function _allocScoreMoney($cart){
        $allocOrderMoney = $cart['scoreMoney'];//待分配的金额
        $allocOrderScore = $cart['useScore'];//待分配的积分
        $totalMoney = $cart['all_freight'] + $cart['all_sum'];//总金额
        foreach ($cart['shop_sum'] as $shop_id =>$shop_sum){
            $orderScore[$shop_id]['useMoney'] = 0;
            $orderScore[$shop_id]['useScore'] = 0;
            $shopMoney = $shop_sum+$cart['shop_freight'][$shop_id];//店铺金额
            //分配金额
            $allocMoney = round($cart['scoreMoney']*$shopMoney/$totalMoney,2);
            //剩余的金额
            $allocTmpMoney = $allocOrderMoney - $allocMoney;
            //修正误差.
            if($allocTmpMoney<0){
                $allocMoney = $allocOrderMoney;
            }else {
                $allocOrderMoney = $allocTmpMoney;
            }

            //分配的积分
            $allocScore = User::ScoreToMoney($allocMoney,true);
            //剩余的积分
            $allocTmpScore = $allocOrderScore - $allocScore;
            //有可能计算出来金额比实际上还要大，修正分数
            if($allocTmpScore<0){
                $allocScore = $allocOrderScore;
            }else{
                $allocOrderScore = $allocTmpScore;
            }
            $orderScore[$shop_id]['useMoney'] = $allocMoney;
            $orderScore[$shop_id]['useScore'] = $allocScore;
        }
        return $orderScore;
    }

    /**
     * 购物车分组计算(各店铺运费及金额)
     * @param array $params 表单请求参数
     * @param array $list 购物车列表
     * @return array
     */
    public function _getOrderMoney($params, $list){
        //按店铺、计费方式汇总的重量或件数
        $shopFreightArr = [];
        //if($params['areaId']>0 && $params['deliverType']==0 ) {
            $shopWeightArr = [];
            foreach ($list as $key => $v) {
                if (!isset($shopWeightArr[$v["shop_id"]][$v["freighttype"]]))
                    $shopWeightArr[$v["shop_id"]][$v["freighttype"]] = 0;
                //设置店铺运费初值
                if (!isset($shopFreightArr[$v["shop_id"]]))
                    $shopFreightArr[$v["shop_id"]] = 0;
                switch ($v['freighttype']) {
                    case 2:
                        $shopWeightArr[$v["shop_id"]][2] += $v['num'] * $v['weight'];
                        break;
                    case 3:
                        $shopWeightArr[$v["shop_id"]][3] += $v['num'];
                        break;
                    case 4:
                        $shopWeightArr[$v["shop_id"]][4] = [];
                        if ($v['weight'] > 0) {
                            if (!isset($shopWeightArr[$v["shop_id"]][4][2]))
                                $shopWeightArr[$v["shop_id"]][4][2] = 0;
                            $shopWeightArr[$v["shop_id"]][4][2] += $v['num'] * $v['weight'];
                        } else {
                            if (!isset($shopWeightArr[$v["shop_id"]][4][3]))
                                $shopWeightArr[$v["shop_id"]][4][3] = 0;
                            $shopWeightArr[$v["shop_id"]][4][3] += $v['num'];
                        }
                        break;
                }
            }
            //按店铺的重量或件数计算运费
            foreach ($shopWeightArr as $key => $v) {
                $freight = 0;
                if (isset($v[2])) {
                    $freight = Freight::orderFreight($key, $params['areaId'], 2, $v[2]);
                } elseif (isset($v[3])) {
                    $freight = Freight::orderFreight($key, $params['areaId'], 3, $v[3]);
                } elseif (isset($v[4])) {
                    if (isset($v[4][2])) {
                        $freight = Freight::shopFreight($key, $params['areaId'], 2, $v[4][2]);
                    }
                    if (isset($v[4][3])) {
                        $freight = Freight::shopFreight($key, $params['areaId'], 3, $v[4][3]);
                    }
                }
                $shopFreightArr[$key] += $freight;
            }
        //}
        foreach ($list as $key => $v){
            //店铺小计求和
            if(!isset($shopSumArr[$v["shop_id"]]))
                $shopSumArr[$v["shop_id"]] = 0;
            $shopSumArr[$v["shop_id"]] += $v['total'];

            //组装店铺商品列表
            $shopGoods['num'] = $v['num'];
            $shopGoods['goodsPrice'] = $v['shopprice'];
            $shopGoods['goodscat_ids'] = $v['goodscat_ids'];
            $shopGoods['salespec_id'] = $v['salespec_id'];
            $shopGoods['goodsSpecNames'] = $v['goodsspecs'];
            $shopGoodsList[$v["shop_id"]][$v['goods_id']] = $shopGoods;
        }
        $cart['shop_freight'] = $shopFreightArr;
        $cart['shop_sum'] = $shopSumArr;
        $cart['shop_goods_list'] = $shopGoodsList;

        //购物车总金额
        $cart['all_freight'] = array_sum($shopFreightArr);
        $cart['all_sum'] = array_sum($shopSumArr);

        $cart['maxScore'] = 0;
        $cart['maxScoreMoney'] = 0;
        $cart['isUseScore'][0] = '';//是否使用积分
        $cart['isUseScore'][1] = "style='display:none'";//不显示
        $cart['useScore'] = 0;
        $cart['scoreMoney'] = 0;
        //计算积分抵现,不能超出物品+运费总金额
        $cart['maxScoreMoney'] = $cart['all_freight'] + $cart['all_sum'];//可抵现金
        $maxScore = User::ScoreToMoney($cart['maxScoreMoney'],true);//可用积分
        $cart['maxScore'] = $maxScore;
        //可用积分不能超过用户现有积分
        $user_id = (int)cookie('uid');
        $score = \app\common\model\User::getFieldById($user_id,'score');
        if($maxScore>$score){//可用积分大于用户实有积分，则修改可用积分和可抵现金
            $cart['maxScore'] = $score;//可用积分
            $cart['maxScoreMoney'] = User::ScoreToMoney($cart['maxScore']);//可抵现金
        }
        $cart['realTotalMoney'] = $cart['all_freight'] + $cart['all_sum'];//总计
        //判断是否使用积分
        if($params['isUseScore']){
            //不能比用户积分还多
            $cart['isUseScore'][0] = 'checked';//选中
            $cart['isUseScore'][1] = '';//显示
            if($params['useScore']>$cart['maxScore']) $params['useScore'] = $cart['maxScore'];//使用积分
            $cart['useScore'] = $params['useScore'];
            $cart['scoreMoney'] = User::ScoreToMoney($params['useScore']);//直接抵现
            $cart['realTotalMoney'] = $cart['realTotalMoney'] - $cart['scoreMoney'];//总计扣除
        }
        return $cart;
    }

    /**
     * 计算运费、积分和总商品价格
     * @param int   $uId  用户ID
     * @param array $list 购物车列表
     * @return mixed
     */
    public function getOrderMoney()
    {
        $params = [];
        $params['deliverType'] = input('deliverType/d');
        $params['areaId'] = input('areaId2/d',-1);
        $params['isUseScore'] = input('isUseScore/d');
        $params['useScore'] = input('useScore/d');

        if($this->auth->id > 0) {
            $params['memo'] = input('memo/a',[]);
            $list = \app\common\model\mall\goods\Cart::getCartList(true);
        }else {
            $params['orderRemarks'] = $this->request->param('orderRemarks',"");
            $params['num'] = (int)$this->request->param("num");
            $list = \app\common\model\mall\goods\Cart::getVisitorCart($params['num']);
        }
        //计算各店铺运费及金额
        $cart = $this->_getOrderMoney($params,$list);

        //整理数据，准备渲染到前端
        foreach ($list as $key=>$val) {
            $list[$key]['shoptotal'] = [
                ["title"=>"店铺运费","value"=>number_format($cart['shop_freight'][$val['shop_id']],2)],
                ["title"=>"店铺合计","value"=>number_format($cart['shop_freight'][$val['shop_id']]+$cart['shop_sum'][$val['shop_id']],2)]
            ];
            if($this->auth->id > 0) {
                $list[$key]['carttotal'] = [
                    ["title" => "总计运费", "value" => number_format($cart['all_freight'], 2)],
                    ["title" => "（可用<span id='maxScoreSpan'>" . $cart['maxScore'] .
                        "</span>个积分抵¥<span id='maxScoreMoneySpan'>" . $cart['maxScoreMoney'] .
                        "</span>）<input type='checkbox' id='c-isUseScore' name='row[isUseScore]' autocomplete='off' " .
                        "onclick='javascript:checkScoreBox(this.checked)' dataval='" . $cart['maxScore'] .
                        "' " . $cart['isUseScore'][0] .
                        "/>积分支付 <span id='c-scoreMoney' " . $cart['isUseScore'][1] . ">，使用积分" .
                        "<input type='number' id='c-useScore' name='row[useScore]' style='width:80px;margin-left:5px'" .
                        " class='j-ipt' autocomplete='off' onblur='javascript:getOrderMoney()' value=" . $cart['useScore'] .
                        " min='0' max='" . $cart['maxScore'] . "'/></span>"
                        , "value" => number_format(-$cart['scoreMoney'], 2)],
                    ["title" => "可获积分", "value" => number_format(User::MoneyGiftScore($cart['realTotalMoney']), 0)],
                    ["title" => "总计", "value" => number_format($cart['realTotalMoney'], 2)],
                ];
                $list[$key]['remark'] = isset($params['memo'][$val["shop_id"]]) ? $params['memo'][$val["shop_id"]] : "";
            }else{
                $list[$key]['carttotal'] = [
                    ["title" => "总计运费", "value" => number_format($cart['all_freight'], 2)],
                    ["title" => "总计", "value" => number_format($cart['realTotalMoney'], 2)],
                ];
                $list[$key]['remark'] = $params['orderRemarks'];
            }
        }
        return $this->request->isAjax()?json($list):$list;
    }

    /**
     * 订单支付代码选择，视情转入订单完成页面。
     */
    public function onlinePayCode(){
        $rs = $this->model->getByUnique();
        $this->assign('object',$rs);
        if(!empty($rs['list'])){
            //如果支付方式为在线支付，则转入支付页面
            if($rs['payType']==1 && $rs['totalMoney']>0){
                $this->assign('orderNo',input("get.orderNo",$rs['orderunique']));
                $this->assign('isBatch',(int)input("get.isBatch/d",1));
                $this->assign('rs',$rs);
                return $this->fetch('online_pay_code');
            }else{
                //如果支付方式为货到付款，则转入完成页面
                return $this->fetch('order_success');
            }
        }else{
            $this->error('未找到待支付的订单','/addons/mall/cart/index');
        }
    }

    /**
     * 订单支付提交
     */
    public function submit(){
        $paymoney = $this->request->request('paymoney');
        $paycode = $this->request->request('paycode');
        $orderNo = $this->request->request('orderNo');
        $isBatch = (int)$this->request->request('isBatch');

        //使用余额支付
        if ($paycode == 'balance') {
            $this->success("即将进入余额支付！",addon_url("mall/wallets/getWalletsUrl",["orderNo"=>$orderNo,"isBatch"=>$isBatch]));
        }

        try {
            \addons\mall\library\Order::submit($isBatch, $orderNo, $paymoney, $paycode ? $paycode : 'wechat');
        } catch (OrderException $e) {
            if ($e->getCode() == 1) {
                //支付成功，则删除session的购物车商品
                if(!cookie("uid")) {
                    session('TMP_CARTS', null);
                }
                $this->success($e->getMessage(), $this->request->server('http_referer'));
            } else if ($e->getCode() == 2) {
                $this->redirect($e->getData());
            } else {
                $this->error($e->getMessage());
            }
        } catch (Exception $e) {
            $this->error($e->getMessage());
        }
        return;
    }

    /**
     * 企业支付通知和回调
     * @throws \think\exception\DbException
     */
    public function epay()
    {
        $type = $this->request->param('type');
        $paycode = $this->request->param('paycode');
        if ($type == 'notify') {
            $pay = \addons\epay\library\Service::checkNotify($paycode);
            if (!$pay) {
                echo '签名错误';
                return;
            }
            $data = $pay->verify();
            try {
                $payamount = $paycode == 'alipay' ? $data['total_amount'] : $data['total_fee'] / 100;
                //\addons\mall\library\Order::settle($data['out_trade_no'], $payamount);
            } catch (Exception $e) {

            }
            echo $pay->success();
        } else {
            $pay = \addons\epay\library\Service::checkReturn($paycode);
            if (!$pay) {
                $this->error('签名错误');
            }
            //微信支付没有返回链接
            if ($pay === true) {
                $this->success("请返回网站查看支付状态!", "");
            }
            $data = $pay->verify();

            $order = \addons\mall\model\Order::get($data['out_trade_no']);
            if (!$order) {
                $this->error('订单未找到');
            }
            $this->success("恭喜你！支付成功!", $order->url);
        }
        return;
    }

    public function wechat()
    {
        $id = $this->request->request('id');
        $order = \addons\mall\model\Order::get($id);
        if (!$order) {
            $this->error('订单未找到');
        }
        if ($this->request->isAjax()) {
            if ($order['status'] == 'paid') {
                $model = Service::getModelByType($order['type'], $order['source_id']);
                if (!$model) {
                    $this->error("未找到文档");
                }
                $this->success("支付成功", $model->url);
            } else {
                $this->error("暂未支付");
            }
        }
        if ($order['status'] == 'paid') {
            $this->error('订单已支付，请勿重复支付');
        }

        $code_url = $this->request->request('code_url');

        $this->view->assign('title', "微信支付");
        $this->view->assign('__order__', $order);
        $this->view->assign('code_url', $code_url);
        return $this->view->fetch();
    }

}
